﻿using UnityEngine;
using System.Collections;

public class ToothScript : MonoBehaviour 
{    
    public bool IsOn{get{return isOn;}set{isOn = value;}}
    private bool isOn = true;
    //private Vector3 startPos;
    private bool iEOn = false;
    private bool isToothBad = false;
    public Texture badTooth;

    
	void Start() 
    {

	}

    void OnSpawned()
    {
        isOn = true;       
    }

    public void AddHit()
    {

    }

    public bool GetToothClickable()
    {
        return !iEOn;
    }

    public bool GetToothBadness()
    {
        return isToothBad;
    }

    private IEnumerator FlyAndDie()
    {
        transform.parent = null;
        transform.Translate(0, 0, -1);
        gameObject.layer = 0;

        iEOn = true;
        float t = 0;
        float time = 2.0f;
        float toothSizeSpeed = Random.Range(4.0f, 7.0f) / 100;
        float SizeSlowingF = 0.15f;             
        int randomX = Random.Range(1,3);
        int randomY = Random.Range(1,3);   
        Vector3 speed = new Vector3((Random.Range(30, 50) * Mathf.Pow(-1, randomX)) / 10, (Random.Range(20, 50) * Mathf.Pow(-1, randomY)) / 10, 0);   
        float slowingF = 0.99f;
        float speedR = Random.Range(0, 600) - 300;       

        while ( t / time < 1)
        {
            t += Time.deltaTime;
            speed = new Vector3(speed.x * slowingF, speed.y * slowingF, 0);
            speedR *= slowingF;
            transform.position += speed * Time.deltaTime;
            transform.eulerAngles = new Vector3(transform.eulerAngles.x, transform.eulerAngles.y, transform.eulerAngles.z + speedR * Time.deltaTime);

            toothSizeSpeed -= Time.deltaTime * SizeSlowingF;
            if (transform.localScale.x + toothSizeSpeed > 0)
            {
                transform.localScale = new Vector3(transform.localScale.x + toothSizeSpeed, transform.localScale.y + toothSizeSpeed, transform.localScale.z + toothSizeSpeed);
            }

            if (transform.localScale.x < 0.2)
            {
                isOn = false;
                StopCoroutine("FlyAndDie");                
                transform.GetComponent<MeshRenderer>().enabled = false;
                Destroy(this.gameObject, 0.1f);
            }

            yield return null;
        }        

        isOn = false;
        Destroy(this.gameObject, 0.1f);
    }

    public void SetToothBad()
    {
        renderer.material.SetTexture("_MainTex", badTooth);
        isToothBad = true;
    }

    public void FlingTooth()
    {
        StartCoroutine(FlyAndDie());
    }
}
